<template>
  <div class="main_spac1" style="padding-bottom: 5px">
    <div class="main_white">
      <div class="main_crumbs boxdq">
        <div class="main_crumbs_l">
          <a href="javascript:;" @click="$router.back(-1)">
            <i class="el-icon-arrow-down"></i>返回
          </a>
          <em>|</em>
          <span>{{ goodsId ?  '编辑套餐' : '新增套餐'}}</span>
        </div>
      </div>
      <div class="main_tile boxdq marginTop10">
        <div class="main_tile_l"><em></em>基本信息</div>
        <div class="flex mg-l-34">
          <el-checkbox v-model="isListing">上架</el-checkbox>
        </div>
      </div>
      <div class="flex mg-t-10">
        <div class="detail-info"><span>*</span><p>套餐名称：</p></div>
        <el-input ref="nameInput" v-model="name" placeholder="请输入套餐名称" maxlength="10" show-word-limit></el-input>
      </div>
      <div class="main_tile">
        <div class="main_tile_l"><em></em>导入图片</div>
      </div>
      <div class="detail-info"> <span>*</span><p>首张为主图，图片尺寸800*800px，大小≤6MB，支持JPG、PNG、JPEG，最多支持5张</p></div>
      <div class="">
        <div class="marginTop20 paddingBottom20 mg-l-10">
          <el-upload
            ref="upload"
            :headers="{
              Authorization:getToken()
            }"
            :action="uploadPath"
            list-type="picture-card"
            :on-success="handSuccess"
            :before-upload="beforeUpload"
            :on-preview="handlePictureCardPreview"
            multiple
            :file-list="filelist"
            :limit="5"
            :on-exceed="onExceed"
            :on-remove="handleRemove"
          >
            <span slot="default">
              <svg
                aria-hidden="true"
                class="main_page_svg"
                width="32"
                height="27"
              >
                <use xlink:href="#icon-commodit_camera" />
              </svg>
            </span>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt />
          </el-dialog>
        </div>
      </div>
      <div class="main_tile boxdq marginTop10">
        <div class="main_tile_l"><em></em>套餐组成</div>
      </div>
      <el-button class="marginBottom20 mg-t-10 mg-l-10 add-goods-btn" type="success" @click="changeShow">添加商品</el-button>
      <el-form
        :inline="true"
        :rules="rules"
        :model="formData"
        class="demo-form-inline mg-l-10"
        ref="userListFrom"
        label-width="100px"
      >
        <div class="marginBottom20 main_table goods-table">
          <el-table
            ref="multipleTable"
            v-loading="listLoading"
            :data="formData.tableList"
            element-loading-text="加载中"
            fit
            highlight-current-row
            :header-cell-class-name="this.$verticaline"
            :header-cell-style="tableHeightStyle"
          >
            <el-table-column
              label="图片"
              :show-overflow-tooltip="true"
              width="120"
              class-name="main_hei"
            >
              <template slot-scope="scope">
                <div :class="{ image_gd: scope.row.pic }">
                  <ul class="box">
                    <li class="">
                      <el-image
                        fit="fill"
                        :src="scope.row.pic"
                        :preview-src-list="[scope.row.pic]"
                      >
                        <div slot="error" class="image-slot">
                          <img :src="puzzleImg" />
                        </div>
                      </el-image>
                    </li>
                  </ul>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="商品名称" prop="goods_name" show-overflow-tooltip/>
            <el-table-column label="单位" prop="unit_name" show-overflow-tooltip/>
            <el-table-column label="组成数量" prop="num" :show-overflow-tooltip="true">
              <template slot-scope="{ row, $index }">
                <el-form-item
                  :prop="'tableList.' + $index + '.num'"
                  :rules="rules.num"
                  label-width="10px"
                  label=" "
                >
                  <el-input class="wid140 num" v-model.trim="row.num" placeholder="请输入" type="number" @input="validateInput(row, $event)"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="市场价" prop="market_price" :show-overflow-tooltip="true" />
            <el-table-column label="最近一次采购价" prop="latest_purchase_price" :show-overflow-tooltip="true" />
            <el-table-column label="管理操作" prop="title" align="center">
              <template slot-scope="scope">
                <el-link type="danger" v-repeatClick @click="deleteGood(scope.row)">删除</el-link>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <div class="mg-l-10">
        <el-button type="primary" @click="saveGoods">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </div>
    <!-- 添加商品 -->
    <dialogAddProduct ref="dialogProduct" :dialogShow="dialogShow" @close="changeShow" @submit="dialogSubmit" :disabledList="formData.tableList"></dialogAddProduct>
  </div>
</template>

<script>
import { uploadPath, puzzleImg } from "@/api/currency";
import dialogAddProduct from './dialog/addProduct.vue'
import { mixins } from "@/mixins/index.js";
import { getInfo } from '@/api/menu.js'

export default {
  mixins: [mixins],
  components: { dialogAddProduct },
  data() {
    return {
      puzzleImg,
      listLoading: false,
      error: [],
      // 上传图片
      filelist: [],
      uploadPath,
      dialogImageUrl: "",
      dialogVisible: false,
      name: '',
      isListing: true,
      imageList: [],
      dialogShow: false,
      rules: {
        num: [
          { required: true, message: "数量不能为空", trigger: "blur" },
          {
            pattern: /^(\d+\.?)?\d{0,2}$/,
            message: "请输入整数和两位小数",
            trigger: "blur"
          }
        ]
      },
      formData: {
        tableList: []
      },
      goodsId: '' //  新增页面没有id，编辑页面有id
    };
  },
  created() {
    this.goodsId = this.$route.query.id || ''
    if(this.goodsId && this.goodsId) {
      this.getData(this.goodsId)
    }
    this.$route.meta.title = this.$route.query.id ? '编辑套餐' : '新增套餐'
  },
  methods: {
    cancel() {
      this.$router.back(-1)
    },
    getData(id) {
      getInfo('/packageGoods/info', {
        id,
      }).then(res => {
        if(res.data) {
          const { name, status, packageGoodsList, img } = res.data
          this.name = name
          this.isListing = Boolean(status)
          this.formData.tableList = packageGoodsList
          this.imageList = img.map(el => {
            return {
              name: el,
              src: el,
              path: el.split('.com')[1],
              url: el
            }
          })
          this.filelist = this.imageList
        }
      })
    },
    handleRemove(file, fileList) {
      this.imageList = this.imageList.filter(el => el.name !== file.name)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.src;
      this.dialogVisible = true;
    },
    // 上传图片-成功
    handSuccess(res, file, fileList) {
      if (res.errcode == 40024) {
        this.error.push(res.errmsg);
      } else {
        this.imageList.push({
          name: file.name,
          path: res.data.path,
          src: res.data.src,
          url: res.data.src,
        });
      }
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传商品图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    onExceed(file, fileList) {
      this.$message.error("上传套餐图片最多支持5张!");
    },
    //  删除商品
    deleteGood(row) {
      this.formData.tableList = this.formData.tableList.filter(el => el.goods_spu_id !== row.goods_spu_id)
    },
    addProduct() {},
    changeShow() {
      this.dialogShow = !this.dialogShow
      if(this.dialogShow) this.$nextTick(() => {
        this.$refs.dialogProduct.getData()
      })
    },
    dialogSubmit(list) {
      const goodsList = list.map(el => {
        el.num = 1
        return el
      })
      this.formData.tableList = this.formData.tableList.concat(goodsList)
    },
    validateInput(row, value) {
      const reg = /^\D*([0-9]\d*\.?\d{0,4})?.*$/
      row.num = +String(value).replace(reg, '$1') || 0.01
      return 
    },
    saveGoods() {
      if(!this.name) {
        this.$message.error('请输入套餐名称！')
        this.$refs.nameInput.focus()
        return false
      }
      if(!this.imageList.length) {
        this.$message.error('请上传导入图片！')
        return false
      }
      if(!this.formData.tableList.length) {
        this.$message.error('请添加商品！')
        return false
      }else {
        if(!this.formData.tableList.every(el => el.num)) {
          this.$message.error('必填项不能为空！')
          return false
        }
      }
      const params = {
        status: this.isListing ? 1 : '0',
        name: this.name,
        goods_list: JSON.stringify(this.formData.tableList.map(el => {
          return {
            "goods_spu_id": el.goods_spu_id,
            "num": el.num,
            "unit": el.unit,
            id: el.id || '0'
          }
        })),
        img: this.imageList.map(el => el.path).join(",")
      }
      if(this.goodsId) params.id = this.goodsId
      let url = this.goodsId ? '/packageGoods/edit' : '/packageGoods/add'
      getInfo(url, params, 'post').then(res => {
        if(res.errcode == 0 && res.data) {
          const message = this.goodsId ? '修改套餐成功' : '新增套餐成功'
          this.$message.success(message)
          setTimeout(() => {
            this.name = ''
            this.imageList = []
            this.formData.tableList = []
            this.filelist = []
            this.$router.push('/menu/goods')
          }, 500)
        }else {
          this.$message.error(res.errmsg)
        }
      }).catch(error => {
        console.log(error);
        
      })
      
    }
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";
.main_white {
  padding: 10px 10px 10px 20px;
}
.add-goods-btn {
  background: #1BA88E;
  border-color: #1BA88E;
  &:hover {
    background: #fff;
    border-color: #1BA88E;
    color: #1BA88E;
  }
}

.main_upImg {
  float: left;
}
.maincp_spe {
  margin-left: 160px;
  margin-top: 10px;
  float: left;
  width: 81%;
  p {
    margin-right: 20px;
    font-size: $font_14;
    color: $colour_red;
    margin-bottom: 10px;
  }
}
.maincp_sp {
  p {
    margin-bottom: 10px;
    line-height: 22px;
    font-size: $font_14;
  }
}
.main_table {
  .image_gd {
    height: 120px;
  }
  .demo-image {
    position: relative;
    margin-left: 20px;
    border: 1px solid #f8f8f9;
    width: 120px;
    overflow: hidden;
    .el-upload-list__item-status-label {
      width: 40px;
      height: 24px;
      background: #13ce66;
      text-align: center;
      -webkit-transform: rotate(45deg);
      transform: rotate(45deg);
      -webkit-box-shadow: 0 0 1pc 1px rgba(0, 0, 0, 0.2);
      box-shadow: 0 0 1pc 1px rgba(0, 0, 0, 0.2);
      display: block;
      i {
        font-size: 12px;
        margin-top: 11px;
        color: $white;
        -webkit-transform: rotate(-45deg);
        transform: rotate(-45deg);
      }
    }
    &:first-child {
      margin-left: 0;
    }
    /deep/.el-image__inner {
      width: 120px;
      height: 120px;
    }
    img {
      width: 120px;
      height: 120px;
    }
  }
}
/deep/.el-upload--picture-card {
  position: inherit;
}
.detail-info {
  font-size: 14px;
  margin: 10px 0 7px 18px;
  display: flex;
  align-items: center;
  span {
    color: #FF4040;
    font-size: 14px;
  }
}
.mg-l-10 {
  margin-left: 10px;
}
.flex {
  display: flex;
  align-items: center;
}
.boxdq {
  justify-content: flex-start;
  .mg-l-34 {
    margin-left: 34px;
  }
}
/deep/.el-upload-list--picture-card .el-upload-list__item {
  width: 120px;
  height: 120px;

  &:first-child {
    margin-left: 0;
  }
}
.num {
  /deep/.el-input__inner {
    padding: 0 0 0 14px;
  }
}
/deep/.goods-table {
  &.main_table .el-table--small td .cell {
    height: 50px;
    line-height: 50px;
  }
  .image-slot {
    width: 50px;
    height: 50px;
    img{
      width: 100%;
    }
  }
  .el-form-item {
    display: flex;
    align-items: center;
  }
}
</style>
